package session;

import entity.User;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.*;
import java.util.Random;

/**
 * @author MissChen
 * @date 2024年05月15日 10:02
 */
@WebServlet("*.code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if ("/show.code".equals(path)) {
            showCode(request, response);
        }
        if ("/register.code".equals(path)) {
            register(request, response);
        }
        if ("/login.code".equals(path)) {
            login(request, response);
        }
        if ("/logout.code".equals(path)) {
            logout(request, response);
        }
        if ("/logout2.code".equals(path)) {
            logout2(request, response);
        }
    }

    public void showCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Random random = new Random();
        //在内存中定义一个画板
        BufferedImage image = new BufferedImage(50, 25, BufferedImage.TYPE_INT_RGB);

        //获取画板中对应的画笔
        Graphics graphics = image.getGraphics();

        //指定画笔填充矩形区域
        graphics.fillRect(0, 0, 50, 25);

        //设置画笔的颜色，设置一个随机色
        graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));

        //设置画笔对应的字体样式
        graphics.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, 18));

        //验证码的内容，要求:随机数字或者英文字母
        String s = "0123456789abcdefghijklmnopqrstuvwxyz";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        //生成验证码后需要用户输入的验证码进行校验
        // 为了便于读取图片中的验证码内容
        // 在此处可以将验证码存到session中去
        request.getSession().setAttribute("code", buffer.toString());
        System.out.println("验证码:" + buffer);

        //将随机生成的字符绘制到图片中
        graphics.drawString(buffer.toString(), 5, 18);

        //输出图片
        ImageIO.write(image, "JPEG", response.getOutputStream());


    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");

            //判断用户名是否重复
            String sql = new StringBuffer()
                    .append(" select id,username,password ")
                    .append(" from t_user ")
                    .append(" where username=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            rs=ps.executeQuery();
            if(rs.next()){
                request.setAttribute("registerMsg","该用户已经被注册");
                request.getRequestDispatcher("/session/register.jsp").forward(request,response);
                return;
            }
            //如果用户名尚未注册，则执行注册业务
            sql = new StringBuffer()
                    .append(" insert into t_user ")
                    .append(" (username,password) ")
                    .append(" values  ")
                    .append(" (?,?) ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2,password);
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/session/login.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","服务器内部异常");
            request.getRequestDispatcher("/session/regsiter.jsp").forward(request,response);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String imageCode = (String) request.getSession().getAttribute("code");

        //输入的验证码和验证码的孩子如果不相等
        if (!code.equals(imageCode)) {
            request.setAttribute("loginMsg", "验证码不正确");
            request.getRequestDispatcher("/session/login.jsp").forward(request, response);
            return;
        }

        //验证用户名密码是否正确
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,username,password ")
                    .append(" from t_user ")
                    .append(" where username=? ")
                    .append(" and password=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));

                //当用户登录成功后，将查询到的用户信息存储session中取
                request.getSession().setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/session/main.jsp");
                return;
            }
            request.setAttribute("loginMsg", "用户名或者密码错误");
            request.getRequestDispatcher("/session/login.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg", "服务器内部异常");
            request.getRequestDispatcher("/session/login.jsp").forward(request, response);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 方式一:直接移除session中的user属性
        request.getSession().removeAttribute("user");
        response.sendRedirect(request.getContextPath() + "/session/main.jsp");
    }

    public void logout2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 方式二:直接清除原有的session(销毁原有的session)
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath() + "/session/main.jsp");
    }
}
